<template>
  <div>
    <div  v-if="isAuth" class="home">
      <search-box :disabled="true" @onClick="onSearchBoxClick" :hot-search="hotWord.name"
      ></search-box>

<!--      <image-card src="http://www.bjqlxy.com/img1/orignal/pics/hv1/35/9/2281/148324355.jpg"-->
<!--                  round-->
<!--      ></image-card>-->

      <books-card :data="shelf" :avatar="avatar"></books-card>

      <banner-card
        :title="banner.title"
        :sub-title="banner.subTitle"
        :image="banner.background"
        @onClick="onBannerClick"
      ></banner-card>

      <div class="container-card-wrapper">
        <container-card title="新鲜上架" btn-text="换一波" @onMoreClick="handleObtainMore('new')"
                        :data="newBooks" :nrows="1" :ncols="3" mode="col"
        ></container-card>
      </div>

      <div class="container-card-wrapper">
        <container-card title="推荐" btn-text="换一波" @onMoreClick="handleObtainMore('recommend')"
                        :data="recommendBooks" :nrows="2" :ncols="2" mode="row"
        ></container-card>
      </div>

      <div class="container-card-wrapper">
        <container-card title="限时免费" btn-text="换一批" @onMoreClick="handleObtainMore('free')"
                        :data="freeBooks" :nrows="1" :ncols="4" mode="col"
        ></container-card>
      </div>

      <div class="container-card-wrapper">
        <container-card title="分类" btn-text="更多分类" @onMoreClick="handleObtainMore('category')"
                        :data="categoryList" :nrows="3" :ncols="2" mode="category"
        ></container-card>
      </div>

    </div>

    <auth-card v-if="!isAuth" @getUserInfo="init"></auth-card>
  </div>
</template>

<script>
  import { getCategories, getHotWords, getBanners, getBooks } from '../../api/api'
  import { getSetting, getUserInfo, setStorageSync, getStorageSync } from '../../api/wechat'
  import SearchBox from '../../components/SearchBox'
  import ImageCard from '../../components/ImageCard'
  import BooksCard from '../../components/BooksCard'
  import BannerCard from '../../components/BannerCard'
  import ContainerCard from '../../components/ContainerCard'
  import AuthCard from '../../components/AuthCard'

  export default {
    data () {
      return {
        isAuth: true,
        hotWord: {},
        avatar: 'http://www.bjqlxy.com/img1/orignal/pics/hv1/35/9/2281/148324355.jpg',
        banner: {},
        shelf: {
          userInfo: {},
          bookCount: 0,
          bookList: []
        },
        newBooks: [],
        newPage: 1,
        recommendBooks: [],
        recommendPage: 1,
        freeBooks: [],
        freePage: 1,
        categoryList: [],
        categoryPage: 1,
        categoryNext: false
      }
    },

    components: {
      AuthCard,
      ContainerCard,
      BannerCard,
      BooksCard,
      SearchBox,
      ImageCard
    },

    methods: {
      obtainFreeBooks (param) {
        getBooks(param).then((response) => {
          // console.log(response.data)
          this.freeBooks = response.data.results
          if (response.data.next === null) this.freePage = 0
        }).catch((error) => {
          console.log(error.response)
          this.freePage = 0
        })
      },
      obtainRecommendBooks (param) {
        getBooks(param).then((response) => {
          // console.log(response.data)
          this.recommendBooks = response.data.results
          if (response.data.next === null) this.recommendPage = 0
        }).catch((error) => {
          console.log(error.response)
          this.recommendPage = 0
        })
      },
      obtainNewBooks (params) {
        getBooks(params).then((response) => {
          // console.log(response.data)
          this.newBooks = response.data.results
          if (response.data.next === null) this.newPage = 0
        }).catch((error) => {
          console.log(error.response)
          this.newPage = 0
        })
      },
      obtainShelf () {
        getBooks({shelf: 1, page_size: 3}).then((response) => {
          // console.log(response.data)
          this.shelf.bookCount = response.data.count
          this.shelf.bookList = response.data.results
        }).catch((error) => {
          console.log(error.response)
        })
      },
      obtainBanners () {
        getBanners({}).then((response) => {
          //  console.log(response.data)
          this.banner = response.data[0]
        }).catch((error) => {
          console.log(error.response)
        })
      },
      obtainHotWords () {
        getHotWords({id: 1}).then((response) => {
          //  console.log(response.data)
          this.hotWord = response.data
        }).catch((error) => {
          console.log(error.response)
        })
      },
      obtainCategories (params) {
        getCategories(params).then((response) => {
          this.categoryList = response.data.results // 不分页可以直接传 data
          if (response.data.next === null) this.categoryPage = 0
          // console.log(response.data)
        }).catch((error) => {
          console.log(error.response)
          this.categoryPage = 0
        })
      },
      onSearchBoxClick () {
        // console.log('跳转到搜索界面')
        // 跳转到搜索界面
        this.$router.push({
          path: '/pages/search/main',
          query: { hotSearch: (this.hotWord && this.hotWord.name) || '' }
        })
      },
      onBannerClick () {
        // 跳转banner 详情页
      },
      handleObtainMore (kind) {
        switch (kind) {
          case 'new':
            this.newPage += 1
            this.obtainNewBooks({ordering: '-add_time', page_size: 3, page: this.newPage})
            break
          case 'recommend':
            this.recommendPage += 1
            this.obtainRecommendBooks({ordering: '-add_time', page_size: 4, page: this.recommendPage})
            break
          case 'free':
            this.freePage += 1
            this.obtainFreeBooks({page_size: 4, page: this.freePage})
            break
          case 'category':
            this.categoryPage += 1
            this.obtainCategories({page_size: 6, page: this.categoryPage})
            break
          default:
            break
        }
      },
      obtainSetting () {
        getSetting(
          'userInfo',
          () => {
            // console.log('获取权限成功')
            this.isAuth = true
            this.obtainUserInfo() // 获取用户信息

            // 获取数据
            this.obtainCategories({page_size: 6})
            this.obtainHotWords()
            this.obtainBanners()
            this.obtainShelf()
            this.obtainNewBooks({ordering: '-add_time', page_size: 3})
            this.obtainRecommendBooks({recommend: 'yes', page_size: 4})
            this.obtainFreeBooks({free: true, page_size: 4})
          },
          () => {
            console.log('没有权限')
            this.isAuth = false
          }
        )
      },
      obtainUserInfo: function () {
        getUserInfo(
          (userInfo) => {
            this.avatar = userInfo.avatarUrl
            setStorageSync('userInfo', userInfo)
            //  检测openId
            const openId = getStorageSync('openId')
            if (!openId || openId.length === 0) {
              // console.log('用code获取openId')
            } else {
              // console.log('有openId')
            }
          },
          () => {
            console.log('获取用户信息失败')
          }
        )
      },
      init () {
        this.obtainSetting()
      }
    },

    mounted () {
      this.init()
      //  获取公共数据
    },

    created () {
      // let app = getApp()
    }
  }
</script>

<style scoped lang="scss">
  .home {
    .container-card-wrapper {
      margin-top: 10px;
    }
  }

</style>
